import myMath from '../../../public/js/myservice/common/my-math'
import angular from 'angular'
import '@yunke/jquery_pagination'
import 'angular-ui'
import '../../../public/js/myservice/contract/contract-common'
import util from '@yunke/core/util'
import { map, chain, includes, sumBy, find } from "lodash"
import { isSpecial } from '../util';
import ui from '@yunke/core/ui';

const apiPrefix = window.G_CONFIG.api_prefix; //api前缀

angular.module('ContractIncome', ['ContractCommonService'])
    .controller('contractIncomeCtrl', ['$scope', '$routeParams', 'contractCommonService','$filter', function ($scope, $routeParams, contractCommonService,$filter) {
        const contractId = $routeParams.id;

        // 合同签署公司下拉框处理
        $scope.ddlConfigCompany = {
            allowClear: false,
            data: [{ id: 1, text: '明源云客' }],
            placeholder: '账套公司'
        };

        //获取合同信息
        contractCommonService.getContract(contractId, function (data) {
            if (data) {
                //获取公司下拉信息
                contractCommonService.actionGetContractAccountCompanyList(data.contract.contract_property_id, function (data2) {
                    const ddlData = map(data2, item => ({
                        id: item.account_company_id,
                        text: item.account_company_name
                    }))
                    $scope.ddlConfigCompany.data = ddlData;
                    $scope.contractBaseInfo = data.contract;
                    $scope.productTotalAmount = sumBy(data.application, item => Number(item.amount))// 产品总额
                    $scope.contractBaseInfo.account_company_id = $scope.contractBaseInfo.account_company_id || chain(ddlData).head().get("id").value()
                    $scope.$applyAsync();
                });
            }
        });

        // contractCommonService.getBussAccountTypes(function (data) {
        //     $scope.ddlConfigIncomeCategoryData = _.compact(_.map(data, function (item) {
        //         return {id: item.type_id, text: item.finance_type_name};
        //     }));
        // });

        //收入类别
        $scope.ddlConfigIncomeCategory = {
            allowClear: false,
            data: [],
            placeholder: '核算收入类别',
            onchange2(newVal, scope) {
                if (scope) {
                    scope.type_name = newVal.text;
                }
            }
        };
        //收入类别
        $scope.ddlConfigFinance = {
            allowClear: false,
            data: [],
            placeholder: '核算收入类别',
            onchange2(newVal, scope) {
                if (scope) {
                    scope.finance_type_name = newVal.text;
                }
            }
        };
        //获取核算收入类别下拉信息
        contractCommonService.getBussAccountTypes(function (data) {
            $scope.ddlConfigIncomeCategory.data = map(data, item => ({ id: item.type_id, text: item.type_name }));
            $scope.ddlConfigFinance.data = map(data, item => ({ id: item.type_id, text: item.finance_type_name }));
            $scope.$applyAsync();
        });

        //收入信息
        $scope.incomes = [];
        $scope.revenueInfo = {};

        //获取收入
        const getContractRevenue = async function () {
            const data = await contractCommonService.getContractRevenue(contractId);
            $scope.revenueInfo = data;
            $scope.incomes = data.revenueList;
            _.map($scope.incomes,function(n,v,s){
                n.amount = parseFloat(n.amount);
                return n;
            });

            $scope.sum_all = _.sumBy($scope.incomes,'amount');
            $scope.sum_one_time = _.sumBy(_.filter($scope.incomes,['revenue_type','7f94a5d3-fcf6-11e4-bed8-00155d02c832']),'amount');
            $scope.sum_rent_time = _.sumBy(_.filter($scope.incomes,['revenue_type','7f94a49d-fcf6-11e4-bed8-00155d02c832']),'amount');
            $scope.sum_ad = _.sumBy(_.filter($scope.incomes,['revenue_type','6ee86ae4-7284-11e7-b033-00155d02c83e']),'amount') + _.sumBy(_.filter($scope.incomes,['revenue_type','39bbb94c-b6e3-11e6-91fa-1051721b3b63']),'amount');
            $scope.sum_sale = _.sumBy(_.filter($scope.incomes,['revenue_type','45b9476d-d3f9-11e6-91fa-1051721b3b63']),'amount');

            $scope.sum_all = $scope.sum_all.toFixed(2);
            $scope.sum_one_time = $scope.sum_one_time.toFixed(2);
            $scope.sum_rent_time = $scope.sum_rent_time.toFixed(2);
            $scope.sum_ad = $scope.sum_ad.toFixed(2);
            $scope.sum_sale = $scope.sum_sale.toFixed(2);
            $scope.$applyAsync();
        };

        getContractRevenue();

        $scope.onSelectRevenue = async (revenue) => {
            if ($scope.selectedRevenue !== revenue) {
                $scope.selectedRevenue = revenue;
                revenue.__loadingRecognition = true;
                const revenueRecognitionList = await contractCommonService.getRevenueRecognitionList(revenue.revenue_id);
                revenue.__loadingRecognition = false;
                $scope.revenueRecognitionList = revenueRecognitionList;
                $scope.$applyAsync();
            } else {
                $scope.selectedRevenue = null;
            }
        };

        $scope.updateRecognition = async (recognition) => {
            ui.loading();
            try {
                const res = await contractCommonService.updateRecognitionByRevenueId(recognition.recognition_id, recognition.recognition_amount);

                if (res) {
                    recognition.editMode = 0;

                    getContractRevenue();

                    $scope.$applyAsync();
                } else {
                    util.alert('修改失败');
                }
            } catch (err) {
                // nothing
            }
            ui.removeLoading();
        };

        $scope.addIncome = function () {
            /**
             * 新增收入
             */
            $scope.incomes.push({
                editMode: 1,
                is_carry_over: false,
                recognized_bad_debt_amount: 0,
                unrecognized_bad_debt_amount: 0,
                kingdee_bad_debt_amount: 0,
                __type: 'add',
                parent_id:'',
                maintain_remark: '手动添加收入项',
                amount: $scope.contractBaseInfo.sign_amount,
                revenue_type: "7f94a49d-fcf6-11e4-bed8-00155d02c832"
            });
        };

        function editIncome(item) {
            /**
             * 编辑收入
             * @type {number}
             */
            //先保存原始数据
            item.orginalData = angular.copy(item);
            item.editMode = 2;
        }

        function editIncomeType(item) {
            /**
             * 编辑收入类别
             * @type {number}
             */
            //先保存原始数据
            item.orginalData = angular.copy(item);
            item.editMode = 3;
        }

        $scope.allowEdit = (record, contractBaseInfo) => {
            const editMode = (record.editMode || 0) === 0 // 什么垃圾写法= =
            return (
                editMode &&
                includes([0, 2], Number(contractBaseInfo.contract_status)) &&
                includes([undefined, 3], record.state)//未推送状态 或者没值
            )
        }
        $scope.edit = (record, contractBaseInfo) => {
            if (Number(contractBaseInfo.contract_status) === 0) {
                editIncome(record)
            } else {
                editIncomeType(record)
            }
        }
        $scope.editIncomeOk = function (item) {
            /**
             * 保存收入信息
             * @type {number}
             */
            if (!item.revenue_type) {
                util.alert('核算收入类别不能为空');
                return;
            }

            if (item.amount == null) {
                util.alert('收入金额不能为空');
                return;
            }
            if (!item.amount.toString().match(/^[\d]*(\.[\d]+)*$/ig)) {
                util.alert('收入金额必须为大于0的数值');
                return;
            }

            if (!parseFloat(item.amount)) {
                util.alert('收入金额必须为大于0的数值');
                return;
            }

            if (item.ddl2Category) {
                item.categoryName = item.ddl2Category.text;
            }

            item.editMode = 0;
        };

        $scope.editIncomeCancel = function (item, idx) {
            /**
             * 取消保存
             * @type {number}
             */

            if (Number(item.editMode) === 1) {
                $scope.incomes.splice(idx, 1);
            } else {
                angular.extend(item, item.orginalData);
                item.editMode = 0;
            }
        };
        $scope.isSpecial = isSpecial;
        $scope.delIncome = function (item) {
            util.confirm('确定要删除此收入吗？', {
                async ok() {
                    ui.loading();
                    try {
                        await contractCommonService.delRevenueByRevenueId(item.revenue_id);
                        $scope.incomes = $scope.incomes.filter(it => it !== item);
                        $scope.$applyAsync();
                        ui.removeLoading();
                    } catch (err) {
                        ui.removeLoading();
                        util.alert(err.message);
                    }
                }
            });
        };

        $scope.stopPropagation = (e) => {
            e.stopPropagation()
        };

        $scope.saveRevenue = function (revenue, parmas = {}) {
            ui.loading();
            const baseInfo = $scope.contractBaseInfo;
            util.myAjax({
                url: apiPrefix + "/contract/submit-revenue",
                type: "POST",
                context: this,
                data: {
                    contractId,
                    revenueList: [{ ...revenue, ...parmas, __type: revenue.revenue_id ? 'update' : 'add' }],
                    accountCompanyId: baseInfo.account_company_id
                },
                success(json) {
                    ui.removeLoading();
                    if (json.retCode === "0") {
                        const revenueCache = revenue.revenue_id && find($scope.incomes, (item) => item.revenue_id === revenue.revenue_id);

                        const revenueFromServer = json.data.revenueList[0];
                        if (revenueCache) {
                            Object.assign(revenueCache, revenueFromServer);
                            revenueCache.__type = 'edit';
                            revenueCache.editMode = 0;
                        } else {
                            Object.assign(revenue, revenueFromServer);
                            revenue.__type = 'edit';
                            revenue.editMode = 0;

                            getContractRevenue();
                        }

                        $scope.$applyAsync();
                        util.alert('保存成功');
                    } else {
                        util.alert("保存失败：" + json.errMsg);
                    }
                },
                fail() {
                    ui.removeLoading();
                    util.alert("服务失败");
                }
            });
        }


        /**
         * 添加收入信息
         * @param $dialog
         * @param $dialogScope
         * @param $data
         */
        $scope.onIncomeRedFlushAddShow = function ($dialog, $dialogScope,revenue) {
            $dialogScope.ddlConfigIncomeCategory = {
                allowClear: false,
                data: $scope.ddlConfigFinance.data,
                placeholder: '核算收入类别',
                onchange2: function (newVal, scope) {
                    if (scope) {
                        $dialogScope.incomeInfo.type_name = newVal.text;
                        $dialogScope.incomeInfo.revenue_type = newVal.id;
                        $dialogScope.incomeInfo.recognized_type = $filter('f_revenue_type')(newVal.id);
                    }
                }
            };

            //获取核算收入类别下拉信息



            $dialogScope.incomeInfo = {
                revenue_type: revenue.revenue_type,
                type_name: revenue.type_name,
                recognized_type: revenue.recognized_type,
                contract_id: revenue.contract_id,
                establish_time: revenue.establish_time,
                begin_on: revenue.begin_on,
                end_on: revenue.end_on,
                amount: -revenue.amount,
                old_income_code: revenue.income_code,
                unrecognized_bad_debt_amount:0,
                recognized_bad_debt_amount:0,
                kingdee_bad_debt_amount:0,
                add_type:1,
                parent_id:revenue.revenue_id,
                __type: 'add',
                maintain_remark: '手动红冲',
            }
            $scope.$applyAsync();
        }

        $scope.saveIncomeRedFlush = function($dialog, $dialogScope){
            var data = $dialogScope.incomeInfo;
            data.add_type = 1;
            var url = apiPrefix + "/contract/add-revenue";
            util.myAjax({
                url: url,
                type: "POST",
                context: this,
                data: {revenue: [data],accountCompanyId: $scope.contractBaseInfo.account_company_id, contractId: contractId},
                async: false,
                success: function (json) {
                    if (json.retCode == 0) {
                        util.alert("操作成功");
                        getContractRevenue();
                        $scope.$applyAsync();
                    } else {
                        util.alert("操作失败：" + json.errMsg);
                        return false;
                    }
                }
            });
        }
    }])
    .filter('sumIncomeAmount2', function () {
        return function (incomes) {
            let amount = 0;
            $.each(incomes, function (i, d) {
                if (d['__type'] == 'delete') {
                    return;
                }
                amount = myMath.add(amount, parseFloat(d.amount));
            });
            return amount;
        }
    })
    .filter('noEqual', function () {
        return function (incomes, x) {
            return incomes != x
        }
    })
    .filter('remainIncomeAmount', function () {
        return function (incomes, contract) {
            let amount = 0;
            $.each(incomes, function (i, d) {
                if (d['__type'] == 'delete') {
                    return;
                }
                amount = myMath.add(amount, parseFloat(d.amount));
            });
            if (contract) {
                if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                    || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                    //云客签约-直属区域/云客签约-联营区域
                    //收入金额汇总 = 签约金额
                    return myMath.sub(contract.sign_amount, amount);
                }
                //其他：收入金额汇总=结算金额
                return myMath.sub(contract.balance_amount, amount);
            }
            return 0;
        }
    })
    .filter('signOrBalanceAmount', function () {
        return function (contract) {
            if (contract) {
                if (contract.contract_property_id == '7f83719a-fce8-11e4-bed8-00155d02c832'
                    || contract.contract_property_id == '7f8422d0-fce8-11e4-bed8-00155d02c832') {
                    //云客签约-直属区域/云客签约-联营区域
                    //收入金额汇总 = 签约金额
                    return contract.sign_amount;
                }
                //其他：收入金额汇总=结算金额
                return contract.balance_amount;
            }
            return 0;
        }
    })
    .filter('saveEnabled', function () {
        return function (incomes) {
            return $.grep(incomes, function (d, i) {
                return d.editMode == 1 || d.editMode == 2 || d.editMode == 3;
            }).length;
        }
    })
    .filter('f_revenue_type', () => (incomes) => {
        const table = {
            '7f94a49d-fcf6-11e4-bed8-00155d02c832': '按租期分期确认',
            '6ee86ae4-7284-11e7-b033-00155d02c83e': '按授权一次性确认',
            '7f94a5d3-fcf6-11e4-bed8-00155d02c832': '按授权一次性确认',
            '45b9476d-d3f9-11e6-91fa-1051721b3b63': '按项目进度确认',
            '39bbb94c-b6e3-11e6-91fa-1051721b3b63': '按授权一次性确认',
        }
        return incomes ? table[incomes] : incomes
    })
    .filter('Finance', () => (incomes) => {
        const FinanceMap = {
            '7f94a49d-fcf6-11e4-bed8-00155d02c832': '云客租用服务收入项',
            '6ee86ae4-7284-11e7-b033-00155d02c83e': '云客互联网服务收入项',
            '7f94a5d3-fcf6-11e4-bed8-00155d02c832': '云客增值服务收入项',
            '45b9476d-d3f9-11e6-91fa-1051721b3b63': '云客销售收入项',
            '39bbb94c-b6e3-11e6-91fa-1051721b3b63': '云客互联网服务收入项',
        }
        return incomes ? FinanceMap[incomes] : incomes
    })
    .filter("state", () => {
        const stateMap = {
            1: "收入未关闭",
            2: "收入通过手动关闭",
            3: "收入自动关闭",
            4: "已结转",
        }
        return (state) => (stateMap[state] || "")
    })
    .filter('income',(income)=>{
        var num = $filter('number')(income, 2);
        if(income + num == 0){
            return income;
        }
        if(income - num == 0){
            return -income;
        }
    });
